<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/BackgroundManage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <!--      <el-breadcrumb-item>权限列表</el-breadcrumb-item>-->
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <!--用户搜索框-->
        <el-col :span="8">
          <el-input placeholder="请输用户名称" clearable v-model="keyword">
            <el-button slot="append" icon="el-icon-search" @click.prevent="sendKeyword"></el-button>
          </el-input>
        </el-col>
        <!--新增用户-->
        <el-col :span="4">
          <el-button type="primary" @click="showAddUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表-->
      <el-table :data="ManagerList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="用户名称" prop="username"></el-table-column>
        <el-table-column label="用户密码">*********</el-table-column>
        <el-table-column label="用户得分" prop="totalScore"></el-table-column>
        <el-table-column label="用户手机" prop="phoneNumber"></el-table-column>

        <el-table-column
            label="用户头像">
          <!--          prop="profilePhoto"-->
          <div class="demo-type">
            <div>
              <el-avatar
                  src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
              />
            </div>
          </div>


        </el-table-column>


        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click.prevent="showUpdate(scope.row.userCode)">修改</el-button>
            <el-button type="danger" size="mini" @click.prevent="del(scope.row.userCode)">删除</el-button>
            <el-button type="danger" size="mini" @click.prevent="endowRole(scope.row.userCode)">赋予角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--赋予角色对话框-->
    <el-dialog title="赋予角色" :visible.sync="endowRoleFormVisible" @close="closeEndowRole"
               :close-on-click-modal="false">
      <br>
      <el-select v-model="roleIdValue" multiple placeholder="请选择角色">
        <el-option v-for="city in citys" :label="city.name" :value="city.id" :key="city.id"></el-option>
      </el-select>


      <div slot="footer" class="dialog-footer">
        <el-button @click.prevent="noEndow">取 消</el-button>
        <el-button type="primary" @click.prevent="endowRoleAdd">赋 予</el-button>
      </div>
    </el-dialog>

    <!--添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addFormVisible" @close="closeAddForm" :close-on-click-modal="false">

      <!--具体表单-->
      <el-form ref="addForm" :rules="addUserInfoRules" :model="addManager" label-width="150px" size="mini">

        <el-form-item label="姓名" prop="username">
          <el-input ref="mobile" v-model="addManager.username" placeholder="请输入姓名" name="username"
                    type="text"
                    tabindex="1" auto-complete="on"/>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input ref="mobile" v-model="addManager.password" placeholder="请输入密码" name="password"
                    type="text"
                    tabindex="1" auto-complete="on"/>
        </el-form-item>

        <el-form-item label="手机账号" prop="phoneNumber">
          <el-input ref="mobile" v-model="addManager.phoneNumber" placeholder="请输入手机" name="phoneNumber"
                    type="text"
                    tabindex="1" auto-complete="on"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改用户-->
    <el-dialog title="修改" :visible.sync="updateFormVisible" @close="closeUpdateForm" :close-on-click-modal="false">
      <!--具体表单-->
      <el-form ref="updateForm" :rules="updatePermissionRules" :model="updateManager" label-width="150px" size="mini">
        <el-form-item label="用户" prop="userName">
          <el-input v-model="updateManager.userName"></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="userPassword">
          <el-input v-model="updateManager.userPassword"></el-input>
        </el-form-item>

        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="updateManager.email"></el-input>
        </el-form-item>

        <el-form-item label="用户手机账号" prop="cellphone">
          <el-input v-model="updateManager.cellphone"></el-input>
        </el-form-item>

        <el-form-item label="账号状态" prop="locked">
          <el-select v-model="updateManager.locked" placeholder="请选择账号状态">
            <el-option label="未上锁" value="0"></el-option>
            <el-option label="已上锁" value="1"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="用户角色:" prop="managerRoleList">
          <span v-for="manager in test">
          <span v-if="manager.roleId == 12">学生|</span>
          <span v-if="manager.roleId == -1">默认|</span>
          <span v-if="manager.roleId == 11">教师|</span>
            <span v-if="manager.roleId == 9">管理员|</span>
        </span>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.prevent="resetPwd">重置密码</el-button>
        <el-button @click.prevent="closeUpdateForm">取 消</el-button>
        <el-button type="primary" @click.prevent="submitUpdateForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.current"
        :page-sizes="[3, 6, 12, 24]"
        :page-size="pageData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total">
    </el-pagination>
  </div>
</template>
<script>
import {reactive, toRefs} from 'vue'
const state = reactive({
  circleUrl:
      'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
})

const {circleUrl, squareUrl,} = toRefs(state)

export default {
  circleUrl: '',
  name: "ManagerMain",
  data() {
    return {
      roleIdValue: [],
      selectedIds: [],
      citys: [{
        id: 12,
        name: '学生'
      },
        {
          id: 11,
          name: '教师'
        },
        {
          id: 9,
          name: '超级管理员'
        },
        {
          id: -1,
          name: '我是默认值'
        }],
      managerRoleList: [],
      endowRoleFormVisible: false,
      test: [],
      updateFormVisible: false,
      updatePermissionRules: {
        userName: [
          {required: true, message: "名称不能为空", trigger: "blur"},
          {min: 2, max: 8, message: "用户名在2到8个字符之间", trigger: "blur"}
        ],
        userPassword: [{
          required: true,
          pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
          message: "不能为空，长度8-20位，必须包含英文大小写+数字",
          trigger: 'blur'
        }],
        email: [
          {required: true, message: "邮箱不能为空", trigger: "blur"}
        ],
        cellphone: [{required: true, message: "手机号不能为空！", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'},
          {min: 11, max: 11, message: "请输入11位的手机号！", trigger: 'blur'}]
      },
      addFormVisible: false,
      addUserInfoRules: {
        username: [{required: true, message: '请输入姓名', trigger: 'blur'},
          {
            validator: function (rule, value, callback) {
              //校验中文的正则：/^[\u4e00-\u9fa5]{0,}$/
              if (/^[\u4e00-\u9fa5]{0,}$/.test(value) == false) {
                callback(new Error("请输入中文"));
              } else {
                //校验通过
                callback();
              }
            }, trigger: 'blur'
          },
        ],
        password: [{
          required: true,
          pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
          message: "不能为空，长度8-20位，必须包含英文大小写+数字",
          trigger: 'blur'
        }],
        phoneNumber: [{required: true, message: "手机号不能为空！", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'},
          {min: 11, max: 11, message: "请输入11位的手机号！", trigger: 'blur'}],
      },
      addManager: {
        username: '',
        password: '',
        phoneNumber: '',
      },
      updateManager: {
        userCode: '',
        userName: '',
        email: '',
        cellphone: '',
        id: '',
        locked: '',
        userPassword: '',
        managerRoleList: []
      },
      roleId: -1
      ,
      keyword: "", //要搜索的人员名称
      ManagerList: [], //人员搜索结果
      pageData: {
        current: 1,
        size: 3,
        total: 4
      }
    };
  },
  methods: {
    noEndow() {
      this.closeEndowRole()
    },
    endowRoleAdd() {
      let config = {
        params: {
          userCode: sessionStorage.getItem("userCode"),
          roleIdValue: this.roleIdValue,
        }
      }
      this.$axios.get("/manager/endowRoleAdd", config).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: "成功",
            type: "success",
            duration: 2000
          })
        }
        if (res.data.code == 500) {
          this.$message({
            message: "错误",
            type: "error",
            duration: 2000
          })
        }
        this.closeEndowRole()
        this.managerList()
      })
    },
    closeEndowRole() {
      this.pageData.current = 1
      this.endowRoleFormVisible = false;
      // this.managerList()
      // this.roleIdValue = '';
    },
    endowRole(userCode) {
      this.endowRoleFormVisible = true
      this.managerRoleList = []
      this.selectedIds = []
      this.roleIdValue = []
      sessionStorage.setItem("userCode", userCode)
      let config = {
        params: {
          userCode: userCode
        }
      }
      this.$axios.get("/manager/endowRole", config).then(
          res => {
            this.managerRoleList = res.data.data.managerRoleList
            this.selectedIds = this.managerRoleList

            for (var i = 0; i < this.selectedIds.length; i++) {
              this.roleIdValue.push(this.selectedIds[i].roleId)
            }
          }
      )
    },
    resetPwd() {
      let config = {
        params: {
          userName: this.updateManager.userName,
          userPassword: this.updateManager.userPassword,
          email: this.updateManager.email,
          cellphone: this.updateManager.cellphone,
          id: this.updateManager.id,
          userCode: this.updateManager.userCode
        }
      }
      this.$axios.get("/manager/resetPwd", config).then(res => {
        this.$message({
          message: "重置成功",
          type: "success",
          duration: 2000
        })
        this.managerList();
        this.pageData.current = 1;
        this.updateFormVisible = false
      })
    },
    del(id) {
      let config = {
        params: {
          userCode: id
        }
      }
      this.$confirm('此操作将永久删除该用户,是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.$axios.get("/manager/delById", config).then(res => {
          let code = res.data.code
          if (code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
              duration: 2000
            })
            this.closeUpdateForm()
            this.managerList()
            this.pageData.current = 1
            return
          }
          this.$message({
            message: "删除失败",
            type: "error",
            duration: 2000
          })
          this.closeUpdateForm()
          this.managerList()
          return
        })
      }).catch(() => {
        //取消
        this.$message({
          type: 'success',
          message: '已取消删除'
        });
      })
    },
    //修改
    submitUpdateForm() {
      this.$refs.updateForm.validate((valid) => {
        if (!valid) {
          this.$message({
            message: "网络波动请重新修改",
            type: "error",
            duration: 2000
          })
          // this.closeUpdateForm()
          return
        }
        let config = {
          userName: this.updateManager.userName,
          userPassword: this.userPassword,
          email: this.updateManager.email,
          cellphone: this.updateManager.cellphone,
          id: this.updateManager.id,
          locked: this.updateManager.locked,
          roleId: this.roleId
        }
        this.$axios.postForm("/manager/updateManager", config).then(res => {
          let code = res.data.code
          if (code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
              duration: 2000
            })
            //更新数据关闭模态框
            this.pageData.current = 1
            this.closeUpdateForm()
            this.managerList()
          }
        })
      })
    },
    closeUpdateForm() {
      this.pageData.current = 1
      this.updateFormVisible = false;
      this.managerList()
    },
    showUpdate(id) {
      let config = {
        params: {
          id: id
        }
      }
      this.$axios.get("/manager/initUpdate", config).then(res => {
        this.updateManager = res.data.data
        this.updateManager.userPassword = ''
        this.test = res.data.data.managerRoleList

        this.roleId = res.data.data.managerRoleList[0].roleId
      })
      this.updateFormVisible = true
    },
    showAddUser() {
      this.addFormVisible = true;
    },
    closeAddForm() {
      this.$refs.addForm.resetFields();
      this.addFormVisible = false;
    },
    //添加用户
    submitAddForm() {
      //判断校验是否成功
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          this.$message({
            message: "网络波动请重新添加",
            type: "error",
            duration: 2000
          })
          this.$refs.addForm.resetFields();
          return
        }
        //校验成功后端添加 对返回值进行 判断取决是否添加成功
        this.$axios.postForm("/manager/addManager", this.addManager).then(res => {
          let code = res.data.code
          if (code == 200) {
            //添加成功
            this.$message({
              message: "好像成功了",
              type: "success",
              duration: 2000
            })
            this.userCode = res.data.data
            this.closeAddForm()

            this.pageData.current = 1
            this.managerList()
          }

          if (code == 500) {
            //添加失败 保险
            this.$message({
              message: "好像不成功",
              type: "error",
              duration: 2000
            })
          }

        })
      })
    },
    sendKeyword() {
      let config = {
        params: {
          current: 1,
          keyword: this.keyword,
          size: this.pageData.size
        }
      }
      this.$axios.get("/manager/managerPageList", config).then(res => {
        this.ManagerList = res.data.data.records
        this.pageData.total = res.data.data.total
      })
    },
    handleSizeChange(size) {
      this.pageData.current = 1;
      this.pageData.size = size;
      this.pageGo();
    },
    handleCurrentChange(currentPage) {
      this.pageData.current = currentPage;
      this.pageGo();
    },
    //页面初始化
    managerList() {
      let config = {
        param: {
          current: this.pageData.current,
          size: this.pageData.size,
          keyword: this.keyword
        }
      }
      this.$axios.get("/manager/managerPageList", config).then(res => {
        this.ManagerList = res.data.data.records
        this.pageData.total = res.data.data.total
      })
    },
    //跳转页面
    pageGo() {
      let config = {
        params: {
          current: this.pageData.current,
          size: this.pageData.size,
          keyword: this.keyword
        }
      }
      this.$axios.get("/manager/managerPageList", config).then(res => {
        this.ManagerList = res.data.data.records
        this.pageData.total = res.data.data.total
      })
    }
  },
  created() {
    this.managerList()
  }

}
</script>
<style lang="less" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader {
  margin-top: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: flex;
}
</style>
